﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="VmMessages.cs" company="Mar3ek">
//   http://mar3ek.wordpress.com
// </copyright>
// <summary>
//   
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Mar3ek.HouseLight
{
    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Threading;
    using System.Windows;
    using System.Windows.Input;
    using LighthouseNET;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public partial class ToolWindowViewModel
    {
        private readonly ICommand _newMessageCommand;
        private readonly ICommand _newCommentCommand;
        private readonly ICommand _modifyMessageCommand;
        private readonly ICommand _deleteMessageCommand;
        private bool _isMessagesEnabled = true;
        private ObservableCollection<Message> _messages;

        /// <summary>
        /// Gets the new message command.
        /// </summary>
        public ICommand NewMessageCommand
        {
            get { return _newMessageCommand; }
        }

        /// <summary>
        /// Gets the modify message command.
        /// </summary>
        public ICommand ModifyMessageCommand
        {
            get { return _modifyMessageCommand; }
        }

        /// <summary>
        /// Gets the delete message command.
        /// </summary>
        public ICommand DeleteMessageCommand
        {
            get { return _deleteMessageCommand; }
        }

        /// <summary>
        /// Gets the new comment command.
        /// </summary>
        public ICommand NewCommentCommand
        {
            get { return _newCommentCommand; }
        }

        /// <summary>
        /// Gets or sets the messages.
        /// </summary>
        /// <value>
        /// The messages.
        /// </value>
        public ObservableCollection<Message> Messages
        {
            get
            {
                return _messages;
            }

            set
            {
                _messages = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Messages"));
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is messages enabled.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is messages enabled; otherwise, <c>false</c>.
        /// </value>
        public bool IsMessagesEnabled
        {
            get
            {
                return _isMessagesEnabled;
            }

            set
            {
                _isMessagesEnabled = value;
                OnPropertyChanged(new PropertyChangedEventArgs("IsMessagesEnabled"));
            }
        }

        /// <summary>
        /// Refreshes the messages.
        /// </summary>
        private void RefreshMessages()
        {
            var t = new Thread(() =>
            {
                try
                {
                    Messages = new ObservableCollection<Message>(_api.GetMessages(_selectedProject.Id));
                }
                catch (Exception)
                {
                    IsMessagesEnabled = false;
                }
            }) { IsBackground = true, Name = "Refresh messages thread" };
            t.Start();
        }

        /// <summary>
        /// Displays the new comment window
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void NewCommentAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var message = (Message)parameter;
            var w = new wNewMessage(_api, SelectedProject.Id, message.ParentId == 0 ? message.Id : message.ParentId) { Owner = _mainWindow };
            w.Closed += MessageWindowClosed;
            w.Show();
        }

        /// <summary>
        /// Handles the Closed event of a wNewMessage
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MessageWindowClosed(object sender, EventArgs e)
        {
            if (((wNewMessage)sender).Result)
            {
                RefreshMessages();
            }
        }

        /// <summary>
        /// Deletes the selected message
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void DeleteMessageAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var message = (Message)parameter;

            var result = MessageBox.Show(
                "Do you really want to delete the selected message? This action cannot be undone.",
                "HouseLight",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            try
            {
                _api.DeleteMessage(SelectedProject.Id, message.Id);
                RefreshMessages();
            }
            catch (LighthouseResponseException ex)
            {
                MessageBox.Show(
                    ex.Message,
                    "HouseLight",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
            catch (LighthouseServerException ex)
            {
                MessageBox.Show(
                    string.Format("A communication error was encountered. Check your internet connection and try again.\nIf the problem persists, contact the plugin developer.\nError details follow:\n\n{0}", ex.Message),
                    "HouseLight",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// Displays the modify message window
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void ModifyMessageAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var w = new wNewMessage(_api, ((Message)parameter)) { Owner = _mainWindow };
            w.Closed += MessageWindowClosed;
            w.Show();
        }

        /// <summary>
        /// Displays the new message window
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private void NewMessageAction(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var w = new wNewMessage(_api, SelectedProject.Id) { Owner = _mainWindow };
            w.Closed += MessageWindowClosed;
            w.Show();
        }
    }
}
